import { createRouter, createWebHistory } from 'vue-router'
import HomeView from '../views/HomeView.vue'
import LoginView from '../views/LoginView.vue'
import PendingInterviewsView from '../views/PendingInterviewsView.vue'
import InterviewHistoryView from '../views/InterviewHistoryView.vue'

const router = createRouter({
  history: createWebHistory(import.meta.env.BASE_URL),
  routes: [
    {
      path: '/home',
      name: 'home',
      component: HomeView,
      meta: { requiresAuth: true }
    },
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'login',
      component: LoginView
    },
    {
      path: '/pending-interviews',
      name: 'pendingInterviews',
      component: PendingInterviewsView,
      meta: { requiresAuth: true }
    },
    {
      path: '/interview-history',
      name: 'interviewHistory',
      component: InterviewHistoryView,
      meta: { requiresAuth: true }
    },
    {
      path: '/interview-detail/:id',
      name: 'interviewDetail',
      component: () => import('../views/InterviewDetailView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/interview-feedback/:id',
      name: 'interviewFeedback',
      component: () => import('../views/InterviewFeedbackView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/interview-room/:id',
      name: 'interviewRoom',
      component: () => import('../views/InterviewRoomView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/interview-room-new/:id',
      name: 'interviewRoomNew',
      component: () => import('../views/InterviewRoomNew.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/add-interview',
      name: 'addInterview',
      component: () => import('../views/AddInterviewView.vue'),
      meta: { requiresAuth: true }
    },
    {
      path: '/about',
      name: 'about',
      component: () => import('../views/AboutView.vue')
    },
    // 捕获所有未匹配的路由，重定向到主页
    {
      path: '/:pathMatch(.*)*',
      redirect: '/home'
    }
  ]
})

// 路由守卫
router.beforeEach((to, from, next) => {
  // 判断是否需要登录
  if (to.matched.some(record => record.meta.requiresAuth)) {
    // 这里应该检查用户是否已登录
    // 对于演示，我们假设登录状态存储在localStorage中
    const isLoggedIn = localStorage.getItem('isLogin') === 'true'
    
    if (!isLoggedIn) {
      // 用户未登录，重定向到登录页
      next({ name: 'login' })
    } else {
      // 用户已登录，允许访问
      next()
    }
  } else {
    // 不需要登录权限的页面
    next()
  }
})

export default router
